C语言的难点~~~`

来源:百度知道 编辑:UC知道 时间:2024/05/30 14:23:06
#include <stdio.h>
# define N 12
typedef struct
{ char num[10];
double s;
} STREC;
double fun (STREC *a,STREC *b, int *n)
{int i;
double sum=0.0,avae=0.0;
for(i=0;i<N;i++)
sum+=a[i].s;
avae=sum/N;
for(i=0;i<N;i++)
if(avae<=a[i].s)
{b[*n]=a[i];*n=*n+1;}
return avae;

}
void main()
{
FILE *wf;
STREC s[N]={{"GA05",85},{"GA03",76},{"GA02",69},{"GA04",85},
{"GA01",91},{"GA07",72},{"GA08",64},{"GA06",87},
{"GA09",60},{"GA11",79},{"GA12",73},{"GA10",90}};
STREC h[N],t;
int i,j,n;
double ave;
ave=fun(s,h,&n);
printf("The %d student data which is higher than %7.3f:\n",n,ave);
for(i=0; i<n; i++)
printf("%s %4.1f\n",h[i].num,h[i].s);
printf("

int i,j,n;

主函数中的变量n没有初始化也没有赋值而直接使用,这是导致越界的原因.修改如下:

//---------------------------------------------------------------------------
#include <stdio.h>
# define N 12
typedef struct
{ char num[10];
double s;
} STREC;
double fun (STREC *a,STREC *b, int *n)
{int i;
double sum=0.0,avae=0.0;
for(i=0;i<N;i++)
sum+=a[i].s;
avae=sum/N;
for(i=0;i<N;i++)
if(avae<=a[i].s)
{b[*n]=a[i];*n=*n+1;}
return avae;

}
void main()
{
FILE *wf;
STREC s[N]={{"GA05",85},{"GA03",76},{"GA02",69},{"GA04",85},
{"GA01",91},{"GA07",72},{"GA08",64},{"GA06",87},
{"GA09",60},{"GA11",79},{"GA12",73},{"GA10",90}};
STREC h[N],t;
int i,j,n=0;/*******注意这里*********/
double ave;
ave=fun(s,h,&n);
printf("The %d student data w